<?php

namespace app\models;

use think\Model;

class Product extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $updateTime = 'updated';



    //商品id 库存增加数量 type 1表示下单 2表示取消下单 sales销量 type类型1下单 2取消 text说明
    public static function SkuEdit($productid, $number, $sales, $type = 0, $text = '')
    {
        if ($number != 0) {
            $product = (new Product())->where('id', $productid)->find();
            if (empty($product)) {
                throw new \Exception("产品不存在", 100);
            }
            //更新
            $res = (new Product())->where(['id' => $product['id']])->inc('sales', $sales)->inc('inventory', $number)->update();
            $res2 = (new ProductSku())->allowfield(true)->save([
                'logid' => floor(microtime(true) * 1000),
                'productid' => $productid,
                'befores' => $product['inventory'],
                'money' => $number,
                'after' => ($product['inventory'] + $number),
                'type' => $type,
                'info' => $text
            ]);
            if (!$res || !$res2) {
                throw new \Exception("操作失败，请重试", 100);
            }
        }
    }
}
